import React, { useState } from 'react';
import { Card, Tabs, Typography, Space, Alert, Collapse, Tag, List, Tooltip } from 'antd';
import {
  QuestionCircleOutlined,
  BulbOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import './style.css';

const { Title, Paragraph, Text } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;

interface ParameterHelpProps {
  contextType?: 'creative' | 'technical' | 'general';
  showExamples?: boolean;
  className?: string;
}

const ParameterHelp: React.FC<ParameterHelpProps> = ({
  contextType = 'general',
  showExamples = true,
  className = ''
}) => {
  const [activeTab, setActiveTab] = useState('basic');

  const parameterGuides = {
    temperature: {
      name: '温度 (Temperature)',
      icon: <BulbOutlined />,
      description: '控制输出的随机性和创造性',
      details: `温度参数决定了模型在选择下一个词时的随机程度。
      • 低温度 (0-0.3): 输出更确定、保守、可预测
      • 中温度 (0.4-0.7): 平衡创造性和一致性
      • 高温度 (0.8-1.0): 输出更随机、创造性、多样化`,
      bestPractices: [
        { scenario: '技术文档、代码生成', value: '0.2-0.4', reason: '需要准确性和一致性' },
        { scenario: '日常对话、问答', value: '0.5-0.7', reason: '平衡流畅性和准确性' },
        { scenario: '创意写作、头脑风暴', value: '0.7-0.9', reason: '需要创新和多样性' },
        { scenario: '诗歌、艺术创作', value: '0.8-1.0', reason: '追求独特性和意外性' }
      ]
    },
    topP: {
      name: 'Top-p (核采样)',
      icon: <PercentageOutlined />,
      description: '控制词汇选择的累积概率阈值',
      details: `Top-p限制模型只考虑累积概率达到p值的最可能的词。
      • 低值 (0.1-0.5): 只选择最可能的少数词
      • 中值 (0.6-0.8): 适度的词汇多样性
      • 高值 (0.9-1.0): 考虑几乎所有可能的词`,
      bestPractices: [
        { scenario: '精确任务', value: '0.5-0.7', reason: '限制在高概率词汇' },
        { scenario: '一般任务', value: '0.8-0.9', reason: '良好的多样性' },
        { scenario: '创意任务', value: '0.9-0.95', reason: '更大的词汇选择空间' }
      ]
    },
    maxTokens: {
      name: '最大Tokens',
      icon: <FileTextOutlined />,
      description: '控制生成内容的最大长度',
      details: `Token是模型处理文本的基本单位。
      • 1 token ≈ 0.75个英文单词
      • 1 token ≈ 0.5个中文字符
      • 代码通常需要更多tokens`,
      bestPractices: [
        { scenario: '简短回答', value: '100-500', reason: '快速响应' },
        { scenario: '标准对话', value: '500-1500', reason: '完整但不冗长' },
        { scenario: '详细解释', value: '1500-3000', reason: '深入的内容' },
        { scenario: '长文创作', value: '3000+', reason: '完整的文章或故事' }
      ]
    },
    presencePenalty: {
      name: '存在惩罚',
      icon: <WarningOutlined />,
      description: '降低重复相同主题的倾向',
      details: `惩罚已经出现过的主题，鼓励谈论新话题。
      • 负值 (-2到0): 允许或鼓励重复
      • 零值 (0): 无惩罚
      • 正值 (0到2): 减少重复，增加话题多样性`,
      bestPractices: [
        { scenario: '技术文档', value: '0', reason: '保持术语一致性' },
        { scenario: '创意写作', value: '0.3-0.6', reason: '避免重复主题' },
        { scenario: '探索性对话', value: '0.6-1.0', reason: '鼓励新话题' }
      ]
    },
    frequencyPenalty: {
      name: '频率惩罚',
      icon: <WarningOutlined />,
      description: '降低逐字重复的倾向',
      details: `基于词频惩罚重复使用的词。
      • 负值 (-2到0): 允许词汇重复
      • 零值 (0): 无惩罚
      • 正值 (0到2): 减少词汇重复`,
      bestPractices: [
        { scenario: '技术写作', value: '0-0.2', reason: '术语需要重复' },
        { scenario: '一般内容', value: '0.3-0.5', reason: '适度避免重复' },
        { scenario: '创意内容', value: '0.5-0.8', reason: '丰富词汇多样性' }
      ]
    }
  };

  const contextRecommendations = {
    creative: {
      title: '创意写作推荐设置',
      icon: <BulbOutlined />,
      settings: {
        temperature: 0.8,
        topP: 0.9,
        maxTokens: 2000,
        presencePenalty: 0.5,
        frequencyPenalty: 0.5
      },
      tips: [
        '使用较高的温度获得更有创意的输出',
        '适度的惩罚参数避免重复',
        '给予足够的token空间展开创意'
      ]
    },
    technical: {
      title: '技术文档推荐设置',
      icon: <CheckCircleOutlined />,
      settings: {
        temperature: 0.3,
        topP: 0.75,
        maxTokens: 1500,
        presencePenalty: 0,
        frequencyPenalty: 0.2
      },
      tips: [
        '低温度确保准确性和一致性',
        '允许必要的术语重复',
        '适中的长度保持简洁'
      ]
    },
    general: {
      title: '通用对话推荐设置',
      icon: <InfoCircleOutlined />,
      settings: {
        temperature: 0.7,
        topP: 0.85,
        maxTokens: 1500,
        presencePenalty: 0.3,
        frequencyPenalty: 0.3
      },
      tips: [
        '平衡的温度适合多数场景',
        '适度避免重复',
        '灵活的长度限制'
      ]
    }
  };

  const commonMistakes = [
    {
      mistake: '温度设置过高导致输出混乱',
      solution: '对于需要准确性的任务，保持温度在0.5以下'
    },
    {
      mistake: '同时使用高温度和低Top-p',
      solution: '这两个参数通常反向调节，高温度配高Top-p，低温度配低Top-p'
    },
    {
      mistake: 'Token限制设置过低',
      solution: '确保Token限制足够完成任务，中文内容需要更多tokens'
    },
    {
      mistake: '惩罚参数设置过高',
      solution: '过高的惩罚会导致输出不自然，通常0.5以下即可'
    }
  ];

  return (
    <Card 
      className={`parameter-help ${className}`}
      title={
        <Space>
          <QuestionCircleOutlined />
          <span>参数使用指南</span>
        </Space>
      }
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="基础概念" key="basic">
          <Collapse defaultActiveKey={['temperature']} ghost>
            {Object.entries(parameterGuides).map(([key, guide]) => (
              <Panel
                header={
                  <Space>
                    {guide.icon}
                    <Text strong>{guide.name}</Text>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {guide.description}
                    </Text>
                  </Space>
                }
                key={key}
              >
                <Paragraph>{guide.details}</Paragraph>
                <Title level={5}>最佳实践</Title>
                <List
                  dataSource={guide.bestPractices}
                  renderItem={item => (
                    <List.Item>
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <Space>
                          <Tag color="blue">{item.scenario}</Tag>
                          <Text code>{item.value}</Text>
                        </Space>
                        <Text type="secondary">{item.reason}</Text>
                      </Space>
                    </List.Item>
                  )}
                />
              </Panel>
            ))}
          </Collapse>
        </TabPane>

        {showExamples && (
          <TabPane tab="场景示例" key="examples">
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              {Object.entries(contextRecommendations).map(([key, rec]) => (
                <Card
                  key={key}
                  size="small"
                  title={
                    <Space>
                      {rec.icon}
                      <span>{rec.title}</span>
                    </Space>
                  }
                  className="context-card"
                >
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <div className="settings-grid">
                      {Object.entries(rec.settings).map(([param, value]) => (
                        <div key={param} className="setting-item">
                          <Text type="secondary">{param}:</Text>
                          <Text code>{value}</Text>
                        </div>
                      ))}
                    </div>
                    <div className="tips-list">
                      {rec.tips.map((tip, index) => (
                        <div key={index} className="tip">
                          <CheckCircleOutlined style={{ color: '#52c41a' }} />
                          <Text>{tip}</Text>
                        </div>
                      ))}
                    </div>
                  </Space>
                </Card>
              ))}
            </Space>
          </TabPane>
        )}

        <TabPane tab="常见错误" key="mistakes">
          <Alert
            message="避免这些常见的参数配置错误"
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <List
            dataSource={commonMistakes}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  avatar={<WarningOutlined style={{ color: '#faad14' }} />}
                  title={<Text strong>{item.mistake}</Text>}
                  description={
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a' }} />
                      <Text>{item.solution}</Text>
                    </Space>
                  }
                />
              </List.Item>
            )}
          />
        </TabPane>

        <TabPane tab="快速参考" key="quick">
          <div className="quick-reference">
            <Title level={5}>参数范围速查</Title>
            <table className="param-table">
              <thead>
                <tr>
                  <th>参数</th>
                  <th>范围</th>
                  <th>默认值</th>
                  <th>说明</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Temperature</td>
                  <td>0 - 1</td>
                  <td>0.7</td>
                  <td>越高越随机</td>
                </tr>
                <tr>
                  <td>Top-p</td>
                  <td>0 - 1</td>
                  <td>0.85</td>
                  <td>越高词汇越多样</td>
                </tr>
                <tr>
                  <td>Max Tokens</td>
                  <td>1 - 模型上限</td>
                  <td>1500</td>
                  <td>输出长度限制</td>
                </tr>
                <tr>
                  <td>Presence Penalty</td>
                  <td>-2 - 2</td>
                  <td>0</td>
                  <td>主题重复惩罚</td>
                </tr>
                <tr>
                  <td>Frequency Penalty</td>
                  <td>-2 - 2</td>
                  <td>0</td>
                  <td>词频重复惩罚</td>
                </tr>
              </tbody>
            </table>

            <Title level={5} style={{ marginTop: 24 }}>Token估算</Title>
            <div className="token-estimation">
              <div className="estimation-item">
                <Text>英文: </Text>
                <Text code>1 token ≈ 4个字符 ≈ 0.75个单词</Text>
              </div>
              <div className="estimation-item">
                <Text>中文: </Text>
                <Text code>1 token ≈ 0.5个字符</Text>
              </div>
              <div className="estimation-item">
                <Text>代码: </Text>
                <Text code>变量较大，通常需要更多tokens</Text>
              </div>
            </div>
          </div>
        </TabPane>
      </Tabs>
    </Card>
  );
};

// Export for importing the icon
const PercentageOutlined: React.FC = () => (
  <span style={{ fontWeight: 'bold' }}>%</span>
);

const FileTextOutlined: React.FC = () => (
  <InfoCircleOutlined />
);

export default ParameterHelp;